package com.hmall.item.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.item.domain.po.Item;
import com.hmall.item.domain.po.ItemDoc;
import com.hmall.item.service.IItemService;
import com.hmall.item.service.ItemEsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RequiredArgsConstructor
@Slf4j
public class ItemEsServiceImpl implements ItemEsService {
    private final RestHighLevelClient client;
    private final IItemService itemService;

    /**
     * 添加(全量更新)商品索引
     * @param itemId
     */
    public void addItem(long itemId){
        // 准备数据
        Item item = itemService.getById(itemId);
        if(item == null || item.getStatus() != 1) return;        // 状态不是1，则为已下架或删除，不加入索引
        ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
        String doc = JSONUtil.toJsonStr(itemDoc);
        // 创建request
        IndexRequest request = new IndexRequest("items").id(itemDoc.getId());
        request.source(doc, XContentType.JSON);
        // 发起请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("添加商品索引异常, 商品ID：{}", itemId, e);
        }
    }

    /**
     * 删除商品索引
     * @param itemId
     */
    public void deleteItem(long itemId) {
        DeleteRequest request = new DeleteRequest("items", String.valueOf(itemId));
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("删除商品索引异常, 商品ID：{}", itemId, e);
        }
    }
}

